package com.ubtechinc.cruzr.launcher2.model.helper;

import android.annotation.SuppressLint;

import com.ubtechinc.cruzr.launcher2.callback.SchedulersListener;

import org.reactivestreams.Subscription;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.FlowableSubscriber;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

@SuppressLint("CheckResult")
public class RxAndroidUtils {
    public static <T> void createFlowable(FlowableOnSubscribe<T> onSubscribe, FlowableSubscriber<T> subscriber){
        Flowable.create(onSubscribe, BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static <T> void createFlowable(FlowableOnSubscribe<T> onSubscribe, FlowableSubscriber<T> subscriber, Consumer<Subscription> consumer){
        Flowable.create(onSubscribe, BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(consumer)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }
    public static void  runOnMain(final SchedulersListener listener) {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                e.onNext("test");
                e.onComplete();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                listener.onMain();
            }
        });
    }
}
